package com.clear.honghefinance.common.exception;

import com.clear.honghefinance.common.dto.entity.ApiResponse;
import com.clear.honghefinance.common.enums.ApiResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;


import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 *
 * @author clear
 */
@RestControllerAdvice   // 用于标识当前类为REST风格对应的异常处理器
// @ControllerAdvice 捕获所有controller出现的异常
@Slf4j
public class GlobalExceptionHandler {
    // @ExceptionHandler用于设置当前处理器类对应的异常类型

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ApiResponse<String> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                                   HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        log.error("请求方式不支持:{}", e.getMessage(), e);
        return ApiResponse.error(e.getMessage());
    }

    /**
     * 请求路径中缺少必需的路径变量
     */
    @ExceptionHandler(MissingPathVariableException.class)
    public ApiResponse<String> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
        return ApiResponse.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
    }

    /**
     * 请求参数类型不匹配
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ApiResponse<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
        return ApiResponse.error(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'",
                e.getName(), e.getRequiredType().getName(), e.getValue()));
    }


    /**
     * <p>
     * 数据校验异常
     * </p>
     * BindException异常处理
     * BindException: 作用于@Validated @Valid 注解
     * 仅对于表单提交参数进行异常处理，对于以json格式提交将会失效
     * 只对实体参数进行校验
     * 注：Controller类里面的方法必须加上@Validated 注解
     *
     * @param e BindException异常对象，包含验证失败的信息
     * @return 返回一个ApiResponse对象，包含错误信息
     */
    @ExceptionHandler(BindException.class)
    public ApiResponse<Object> handleBindException(BindException e) {
        log.error("校验异常BindException {}", e.getMessage(), e);
        ApiResponse<Object> apiResponse = new ApiResponse<>();
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(fieldError ->
                errors.put(fieldError.getField(), fieldError.getDefaultMessage())
        );
        return apiResponse.error(ApiResponseCodeEnum.PARAMETER_INVALID.getCode(), errors);
    }

    /**
     * 业务处理异常
     */
    @ExceptionHandler(ParameterException.class)
    public ApiResponse<Object> handleParameterException(ParameterException e) {
        log.error("参数异常ParameterException: {}", e.getMessage(), e);
        // 返回响应对象
        ApiResponse<Object> apiResponse = new ApiResponse<>();
        apiResponse.setCodeMessage(e.getMessage());
        apiResponse.error(e.getCode(), e.getFieldErrors());
        return apiResponse;
    }

    /**
     * 业务处理异常
     */
    @ExceptionHandler(BizException.class)
    public ApiResponse<Object> handleBizException(BizException e) {
        log.info("BizException:", e);
        // 返回响应对象
        ApiResponse<Object> apiResponse = new ApiResponse<>();
        Map<String, String> errors = new HashMap<>();
        errors.put(ApiResponseCodeEnum.BUSINESS_ERROR.getMessage(), e.getMessage());
        apiResponse.error(e.getCode(), errors);
        return apiResponse;
    }

    /**
     * 业务处理异常
     */
    @ExceptionHandler(LoginException.class)
    public ApiResponse<Object> handleLoginException(LoginException e) {
        // 返回响应对象
        ApiResponse<Object> apiResponse = new ApiResponse<>();
        Map<String, String> errors = new HashMap<>();
        errors.put(ApiResponseCodeEnum.LOGIN_ERROR.getMessage(), e.getMessage());
        apiResponse.error(e.getCode(), errors);
        return apiResponse;
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public ApiResponse<String> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e);
        return ApiResponse.error(e.getMessage());
    }
}
